<template>
	<Card :bordered="false" dis-hover>
		<Button type="primary"@click="openedit(-1)" class="ivu-mb-8"
			v-hasC="{name: '-v1-rbac-action-create',flag: '/v1/rbac/action/create'}">新增</Button>
		<JG-table :params="params" :total="total" :loading="loading" :columns="columns" :data="data"
			:butshow="butshow" @askData="askData" @handleEdit="openedit"  @sortchange="sortchange"   :maxHeight="600"/>
		<Modal v-model="showCreate" :mask-closable="false" :title="edit? '新增' : '编辑'" :loading="true"
			@on-cancel="handleCancel">
			<Form ref="create" :model="createMenuData" :rules="createRules" :label-width="100">
				<FormItem label="动作名称：" prop="name">
					<Input v-model="createMenuData.name" placeholder="请输入动作行为名称" clearable />
				</FormItem>
				<FormItem label="所属模块：" prop="module_id">
					<TreeSelect
						v-model="createMenuData.module_id"
						:data="modulelist"
						@on-change="changemodule"
						v-width="200"
						clearable
					/>
				</FormItem>
				<FormItem label="菜单名称：" prop="menu_id" v-if="
					createMenuData.module_id !== '' &&
						parentMenuLists &&
					parentMenuLists.length > 0
				">
					<TreeSelect
					v-model="createMenuData.menu_id"
					:data="parentMenuLists"
					v-width="200"
					clearable
				/>
				</FormItem>
				<FormItem label="动作路由：" prop="flag">
					<Input v-model="createMenuData.flag" placeholder="请输入路由" clearable />
				</FormItem>
				<FormItem label="排序：" prop="sort">
					<Input v-model="createMenuData.sort" />
				</FormItem>
				<FormItem label="菜单状态：">
					<Switch v-model="createMenuData.status" size="large">
						<span slot="open">开启</span>
						<span slot="close">关闭</span>
					</Switch>
				</FormItem>
			</Form>
			<div slot="footer">
				<Button type="default" @click="handleCancel">取消</Button>
				<Button @click="handleSubmit" type="primary">保存</Button>
			</div>
		</Modal>
	</Card>
</template>
<script>
    import {
        rbacactionlist,
        rbacactioninfo,
        rbacactioncreate,
        rbacactionupdate
    } from '@/api/power.js';
    import mixins from '@/mixins/mixins';
    export default {
        mixins: [mixins],
        data () {
            return {
                butshow: {
                    Edit: {
                        name: '-v1-rbac-action-update',
                        flag: '/v1/rbac/action/update'
                    }
                },
                columns: [
                    { title: '菜单名称', key: 'name', width: 240, tree: true },
                    { title: '所属模块', key: 'module_name', minWidth: 160, sortable: 'custom' },
                    { title: '唯一标识', slot: 'marking', minWidth: 140 },
                    { title: '动作路由', slot: 'flag', minWidth: 140 },
                    { title: '排序', key: 'sort', width: 80 },
                    { title: '状态', slot: 'status', width: 100 },
                    { title: '创建时间', key: 'created_at_str', width: 180 },
                    { title: '操作', slot: 'projectsettingActions', align: 'center', width: 100 }
                ],
                data: [],
                params: {
                    sort_module: '',
                    page: 0,
                    pageSize: 0
                    // keyword:''
                },
                modulelist: [],
                showCreate: false,
                edit: true,
                placeholder: '请先选择模块',
                menu_list: [],
                parentMenuList: {},
                parentMenuLists: [],
                createMenuData: {
                    name: '',
                    flag: '',
                    menu_id: '',
                    module_id: '',
                    status: true,
                    sort: ''
                },
                total: -1,
                createRules: {
                    name: [
                        {
                            required: true,
                            message: '请输入动作行为名称',
                            trigger: 'blur'
                        }
                    ],
                    sort: [
                        {
                            message: '排序必须是正数字',
                            pattern: /^[+]{0,1}(\d+)$/,
                            trigger: 'blur'
                        }
                    ],
                    menu_id: [{ required: true, message: '请选择菜单', trigger: 'change' }],
                    module_id: [{ required: true, message: '请选择模块', trigger: 'change' }],
                    flag: [{ required: true, message: '请输入路由', trigger: 'blur' }],
                    status: [
                        {
                            required: true,
                            message: '请输入动作行为状态',
                            trigger: 'blur'
                        }
                    ]
                }
            };
        },
        methods: {
            initial () {
                this.funaskData = rbacactionlist
                this.askData()
            },
            askDatas (res) {
                this.data = res.list;
            },
            sortchange (e) {
                if (e.key === 'module_name') {
                    this.params.sort_module = e.sort
                }
                this.initial()
            },
            askDatasearch () {
                this.searchData.project.forEach((item) => {
                    if (item.id === 1) {
                        this.params.keyword = item.value
                    }
                })
                this.params.page = 1
                this.askData()
            },
            openedit (row) {
                if (row === -1) {
                    this.createMenuData = {
                        name: '',
                        flag: '',
                        menu_id: '',
                        module_id: '',
                        status: true,
                        sort: ''
                    }
                    this.edit = true
                    this.getParentMenuList(0)
                } else {
                    this.edit = false
                    this.$nextTick(() => {
                        this.$refs['create'].resetFields();
                        // this.updateIndex = index;
                        // const row = this.list[index];
                        for (let key in this.createMenuData) {
                            this.createMenuData[key] = row[key];
                        }
                        this.createMenuData.status = this.createMenuData.status === '1';
                        this.createMenuData.id = row.id;
                        this.getParentMenuList(row.id, this.createMenuData.module_id);
                        this.changemodule(row.menu_id)
                    });
                }
                this.showCreate = true
            },
            handleCancel () {
                this.$refs.create.resetFields();
                this.showCreate = false;
            },
            filterArr (arr, id) {
                arr.forEach((ee) => {
                    if (ee.children && !(ee.children instanceof Array)) {
                        ee.children = [...ee.children[id]];
                        this.filterArr(ee.children);
                    } else {
                        return false;
                    }
                });
                return arr;
            },
            // // 获取父级菜单
            // getParentMenuList (id) {
            //     rbacactioninfo({ id: id }).then((res) => {
            //         this.menu_list = res.menu_list;
            //     });
            // },
            // 获取父级菜单
            getParentMenuList (moduleId, menu) {
                rbacactioninfo({ id: moduleId }).then((res) => {
                    this.parentMenuList = res.menu_list;
                    this.modulelist = res.module_list;
                    // console.log(this.modulelist, 'modulelist')
                    if (menu) {
                        this.changemodule(menu);
                    }
                });
            },
            // 选择模块促发父级菜单名
            changemodule (e) {
                this.parentMenuLists = this.parentMenuList[`${e}`];
            },
            // // 新增数据
            handleSubmit () {
                this.$refs.create.validate((valid) => {
                    if (valid) {
                        let sendData = JSON.parse(JSON.stringify(this.createMenuData));
                        sendData.status = sendData.status === true ? '1' : '0';
                        if (this.edit) {
                            // 新建
                            rbacactioncreate(sendData).then((res) => {
                                // 创建动作行为成功后，刷新页面
                                this.showCreate = false;
                                this.askData();
                                this.$Message.success('新增成功');
                                this.$refs.create.resetFields();
                            });
                        } else {
                            // 修改
                            rbacactionupdate(sendData).then((res) => {
                                // 修改动作行为成功后，刷新页面
                                this.showCreate = false;
                                this.askData();
                                this.$Message.success('编辑成功');
                                this.$refs.create.resetFields();
                            });
                        }
                    }
                });
            }
        }
    };
</script>
